package be.dioubs.sportTrack;

import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import be.dioubs.sportTrack.common.Constant;
import be.dioubs.sportTrack.common.GlobalFormatter;
import be.dioubs.sportTrack.dto.TrackDTO;

public class TrackEditor extends Activity{
	static final int DATE_DIALOG_ID = 0;
	
    private EditText mTitleText;
    private EditText mDescription;
    private EditText mTime;
    private Spinner mSport;
    private EditText mDistanceNb;
    private EditText mDistanceUnit;    
    private Button mDateButton;
    private EditText mHeartRateMoy;
    private EditText mHeartRateMax;
    private EditText mFitnessLevel;
    
    private Long mId;
    private Long mDate;    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.track_editor);
        setTitle(R.string.edit_track);

        mTitleText = (EditText) findViewById(R.id.title);
        mDescription = (EditText) findViewById(R.id.description);
        mSport = (Spinner) findViewById(R.id.spinnerSport);
        mDistanceNb = (EditText) findViewById(R.id.distance_nb);
        mDistanceUnit = (EditText) findViewById(R.id.distance_unit);
        mDateButton = (Button) findViewById(R.id.dateButton);
        mHeartRateMoy = (EditText) findViewById(R.id.heartRateMoy);
        mHeartRateMax = (EditText) findViewById(R.id.heartRateMax);
        mTime = (EditText) findViewById(R.id.time);
        mFitnessLevel = (EditText) findViewById(R.id.fitnessLevel);  
        
        prepareView();
    }
    
    private void prepareView() {
        Button confirmButton = (Button) findViewById(R.id.confirm);
        Button cancelButton = (Button) findViewById(R.id.cancel);
        
        String sports[] = Constant.sports;
        
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        		android.R.layout.simple_spinner_item, sports);
        
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        
        mSport.setAdapter(adapter);

        Bundle extras = getIntent().getExtras();
        
        // Default values
        mId = null;
        String title = "";
        String description = "";
        String sport = "";
        Long distanceNb = 0l;
        String distanceUnit = "";
        mDate = new Date().getTime();
        String date = GlobalFormatter.date(mDate);
        String heartRateMoy = "";
        String heartRateMax = "";
        String time = "";
        String fitnessLevel = "";
        
        if(extras != null) {
        	mId = extras.getLong(TrackDTO.KEY_ID);
            title = extras.getString(TrackDTO.KEY_TITLE);
            description = extras.getString(TrackDTO.KEY_DESCRIPTION);
            sport = extras.getString(TrackDTO.KEY_SPORT);
            distanceNb = extras.getLong(TrackDTO.KEY_DISTANCE_NB);
            distanceUnit = extras.getString(TrackDTO.KEY_DISTANCE_UNIT);
            mDate = extras.getLong(TrackDTO.KEY_DATE);
            date = GlobalFormatter.date(mDate);
            heartRateMoy = extras.getString(TrackDTO.KEY_HEART_RATE_MOY);
            heartRateMax = extras.getString(TrackDTO.KEY_HEART_RATE_MAX);
            time = extras.getString(TrackDTO.KEY_TIME);
            fitnessLevel = extras.getString(TrackDTO.KEY_FITNESS_LEVEL);
        }
        
        mTitleText.setText(title);
        mDescription.setText(description);
        mDistanceNb.setText(distanceNb.toString());
        mDistanceUnit.setText(distanceUnit);
        mDateButton.setText(date);
        mHeartRateMoy.setText(heartRateMoy);
        mHeartRateMax.setText(heartRateMax);
        mTime.setText(time);
        mFitnessLevel.setText(fitnessLevel);
        
        if (sport != null) {
        	int position;
        	
        	if(sport.equals(Constant.SPORT_RUN))
        		position = 0;
        	else if(sport.equals(Constant.SPORT_BIKE))
        		position = 1;
        	else
        		position = 2;
        	
        	mSport.setSelection(position);
        } 
        
        confirmButton.setOnClickListener(onClickConfirm);
        cancelButton.setOnClickListener(onClickCancel);
        mDateButton.setOnClickListener(onClickDate);       
    }
    
	private Bundle prepareExtras() {
		Bundle extras = new Bundle();	
		
		extras.putString(TrackDTO.KEY_TITLE, mTitleText.getText().toString());
		extras.putString(TrackDTO.KEY_DESCRIPTION, mDescription.getText().toString());
		extras.putString(TrackDTO.KEY_SPORT, mSport.getSelectedItem().toString());
		extras.putString(TrackDTO.KEY_TIME, mTime.getText().toString());
		
		if(mDistanceNb != null)
			extras.putLong(TrackDTO.KEY_DISTANCE_NB, Long.parseLong(mDistanceNb.getText().toString()));
		
		extras.putString(TrackDTO.KEY_DISTANCE_UNIT, mDistanceUnit.getText().toString());
		extras.putString(TrackDTO.KEY_HEART_RATE_MAX, mHeartRateMoy.getText().toString());
		extras.putString(TrackDTO.KEY_HEART_RATE_MOY, mHeartRateMax.getText().toString());
		extras.putString(TrackDTO.KEY_FITNESS_LEVEL, mFitnessLevel.getText().toString());

		extras.putLong(TrackDTO.KEY_DATE, mDate);
		
        if(mId != null)
        	extras.putLong(TrackDTO.KEY_ID, mId);

        return extras;
	}	
	
	@Override
	protected Dialog onCreateDialog(int id) {
	    switch (id) {
	    case DATE_DIALOG_ID:
	    	Calendar cal = Calendar.getInstance();
	    	cal.setTimeInMillis(mDate);
	    	int day = cal.get(Calendar.DAY_OF_MONTH);
	    	int month = cal.get(Calendar.MONTH);
	    	int year =  cal.get(Calendar.YEAR);
	    	
	    	return new DatePickerDialog(this, dateSetListener,  year, month, day);
	    }
	    
	    return null;
	}
	
	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
    	Calendar cal = Calendar.getInstance();
    	cal.setTimeInMillis(mDate);
    	int day = cal.get(Calendar.DAY_OF_MONTH);
    	int month = cal.get(Calendar.MONTH);
    	int year =  cal.get(Calendar.YEAR);
    	
    	((DatePickerDialog)dialog).updateDate(year, month, day);
	}
	
	//
	// LISTENERS
	//
	
	// Confirm update
    private OnClickListener onClickConfirm = new OnClickListener() {
        public void onClick(View view) {
            Bundle extras = prepareExtras();

            Intent intent = new Intent();
            intent.putExtras(extras);
            
            setResult(RESULT_OK, intent);
            
            finish();
        }
    };    
    
    // Cancel update
    private OnClickListener onClickCancel = new OnClickListener() {
	    public void onClick(View view) {
	        setResult(RESULT_CANCELED, null);
	        finish();
	    }
    };
    
    // Choose date
    private OnClickListener onClickDate = new OnClickListener() {
	    public void onClick(View view) {
	    	showDialog(DATE_DIALOG_ID);
	    }
    };
    
    // Callback received when the user "sets" the date in the dialog
	private DatePickerDialog.OnDateSetListener dateSetListener =
    		new DatePickerDialog.OnDateSetListener() {
    			public void onDateSet(DatePicker view, int year, 
    					int monthOfYear, int dayOfMonth) {
    				Calendar cal = Calendar.getInstance();
    				cal.set(year, monthOfYear, dayOfMonth);
    				Date date = cal.getTime();
    				mDate = date.getTime();
    				
    				mDateButton.setText(GlobalFormatter.date(mDate));
                }
    };
}
